package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneItemVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 新增查询未被领取的采购单
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        //拼接status条件 0-采购单新建 1-采购单刚分配给某个人
        wrapper.eq("status",0).or().eq("status",1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    /**
     * 合并采购单
     * @param mergeVo
     */
    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        //获取purchaseId 为null还得新建
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null){
            //采购单需要新建
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            //给予创建时间和修改时间的默认值
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            //采购单状态
            purchaseEntity.setStatus(WareConstant.PuchaseStatusEnum.CREATED.getTypeCode());
            this.save(purchaseEntity);
            //设置采购单Id
            purchaseId = purchaseEntity.getId();
        }

        //有采购单id即purchaseId，检查采购单状态是否为0|1 不是则不允许合并
        PurchaseEntity byId = this.getById(purchaseId);
        if (byId.getStatus() == WareConstant.PuchaseStatusEnum.CREATED.getTypeCode() ||
        byId.getStatus() == WareConstant.PuchaseStatusEnum.ASSIGNED.getTypeCode()){
            //采购单需求的采购单合并功能-本质就是一个修改 修改wms_purchase_detail表中
            // id为items中遍历的元素值的purchase_id 和 status
            //获取要变更采购单的Id集合
            List<Long> items = mergeVo.getItems();
            //创建一个标记 即该集合是否可用的依据
            Boolean isCorrect = true;
            for (Long item : items) {
                //查出当前Id对应的PurchaseDetailEntity
                PurchaseDetailEntity purDetailById = purchaseDetailService.getById(item);
                //根据Id查不到PurchaseDetailEntity或存在PurchaseDetailEntity.status的状态有问题直接结束方法
                if (purDetailById == null || (purDetailById.getStatus() != WareConstant.PuchaseDetailStatusEnum.CREATED.getTypeCode() &&
                        purDetailById.getStatus() != WareConstant.PuchaseDetailStatusEnum.ASSIGNED.getTypeCode())){
                    System.out.println("不合理的purchaseDetailEntity："+purDetailById);
                    isCorrect = false;
                    return;
                }
            }
            if (isCorrect){
                //遍历并收集为purchaseDetailEntity集合
                //System.out.println("通过了forEach 所有purchaseDetailEntity合理");
                Long finalPurchaseId = purchaseId;
                List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map(i -> {
                    PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                    purchaseDetailEntity.setId(i);
                    //这里purchaseId必须是final类型的
                    //理由是局部内部类引用外部的变量时外部的变量默认变成final修饰
                    purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                    purchaseDetailEntity.setStatus(WareConstant.PuchaseDetailStatusEnum.ASSIGNED.getTypeCode());
                    return purchaseDetailEntity;
                }).collect(Collectors.toList());
                //注入purchaseDetailService调用批量修改的方法
                purchaseDetailService.updateBatchById(purchaseDetailEntities);
                //修改当前采购单的修改时间
                if (purchaseId != null){
                    PurchaseEntity p = new PurchaseEntity();
                    p.setId(purchaseId);
                    p.setUpdateTime(new Date());
                    this.updateById(p);
                }
            }

        }

    }

    /**
     * 领取采购单 ids采购单集合
     * @param ids
     */
    @Override
    public void received(List<Long> ids) {
        //1.确认当前采购单是新增或已分配的状态
        List<PurchaseEntity> purchaseEntities = ids.stream().map(id -> {
            return this.getById(id);
        }).filter(item -> {
            //过滤状态 只留下新增或已分配的采购单
            if (item.getStatus() == WareConstant.PuchaseStatusEnum.CREATED.getTypeCode() ||
                    item.getStatus() == WareConstant.PuchaseStatusEnum.ASSIGNED.getTypeCode()) {
                return true;
            }
            return false;
        }).map(item->{
            //继续映射 改变状态
            item.setStatus(WareConstant.PuchaseStatusEnum.RECEIVE.getTypeCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        //2.改变采购单的状态
        if (!CollectionUtils.isEmpty(purchaseEntities)){
            this.updateBatchById(purchaseEntities);
        }
        //3.改变采购需求中采购项的状态
        purchaseEntities.forEach(item->{
            //注入purchaseDetailService并新增listDetailByPurchaseId方法
            // 根据采购单ID即purchaseId获取采购需求列表
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listDetailByPurchaseId(item.getId());
            //更新采购需求状态 仅设置好采购需求Id和采购状态即可
            List<PurchaseDetailEntity> collect = purchaseDetailEntities.stream().map(entity -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setStatus(WareConstant.PuchaseDetailStatusEnum.BUYING.getTypeCode());
                purchaseDetailEntity.setId(entity.getId());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            //批量更新采购需求的状态 非空判断
            if (!CollectionUtils.isEmpty(collect)){
                purchaseDetailService.updateBatchById(collect);
            }
        });
    }

    /**
     * 采购完成的处理
     * @param doneVo
     */
    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {

        //1.改变采购项|采购需求的状态
        List<PurchaseDoneItemVo> items = doneVo.getItems();
        //定义一个flag 一旦有一个采购项出错那么该采购单就认为采购失败
        Boolean flag = true;
        //创建一个集合用于收集处理后的采购项
        List<PurchaseDetailEntity> detailList = new ArrayList<>();
        //遍历items分离出成功的采购项和失败的采购项目
        for (PurchaseDoneItemVo item : items) {
            //创建采购项实体类
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            //采购项失败
            if (item.getStatus() == WareConstant.PuchaseDetailStatusEnum.HASERROR.getTypeCode()){
                //采购单采购失败
                flag = false;
                //设置失败采购项状态
                purchaseDetailEntity.setStatus(item.getStatus());
            }else {
                //采购成功
                //设置采购项状态
                purchaseDetailEntity.setStatus(WareConstant.PuchaseDetailStatusEnum.FINISH.getTypeCode());

                //2.采购成功的商品入库
                //根据采购项id查询采购需求 用于后续获取sku_id ware_id stock
                PurchaseDetailEntity purDetailById = purchaseDetailService.getById(item.getItemId());
                //注入wareSkuService并根据sku_id商品id,ware_id仓库id和stock新增库存给商品入库
                wareSkuService.addStock(purDetailById.getSkuId(), purDetailById.getWareId(), purDetailById.getSkuNum());

            }
            //设置采购项Id
            purchaseDetailEntity.setId(item.getItemId());
            //添加进集合中
            detailList.add(purchaseDetailEntity);
        }
        //批量更新采购项集合
        if (!CollectionUtils.isEmpty(detailList)){
            purchaseDetailService.updateBatchById(detailList);
        }

        //3.改变采购单状态
        //获取采购单Id
        Long purchaseId = doneVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setStatus(flag?WareConstant.PuchaseStatusEnum.FINISH.getTypeCode()
                :WareConstant.PuchaseStatusEnum.HASERROR.getTypeCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

    }

}